package com.ruoyi.detection.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.Threads;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.detection.domain.DetectionLog;
import com.ruoyi.detection.service.ModelService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.utils.FileTool;
import com.ruoyi.utils.ImgDrawCircleTool;
import com.ruoyi.utils.ParseString;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 智能检测与识别模型
 * 飞虱模型检测
 *
 * @author Mr-Le
 */
@Api("智能检测模型")
@Slf4j
@RestController
@RequestMapping("/detection")
public class ModelController extends BaseController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ModelService modelService;

    /**
     * 存储文件的路径
     */
    @Value("${ruoyi.profile}")
    private String profile;

    /**
     * 模型检测图像处理路径
     */
    @Value("${ruoyi.detectionUrl}")
    private String detectionUrl;

    @ApiOperation("调用模型检测,示例：http://localhost:8989/detection/model")
    @PostMapping("/model")
    public AjaxResult model(@RequestParam("imageName") MultipartFile file) throws Exception {

        if (!file.isEmpty()) {
            // upload() : 返回的就是文件路径
            String images = FileUploadUtils.upload(RuoYiConfig.getDetectionPath(), file);
            String detectionImages = StringUtils.substringAfter(images, "profile");
            File imgFile = new File(profile + detectionImages);
            String imgCreateTime = FileTool.getImgCreateTime(imgFile);
            /* 解析识别结果构造实例存入数据库并返回, 检测不需要list集合，识别有多个可能，需要集合装载，其他的不需要 */
            List<DetectionLog> detectionLogList = new ArrayList<>();
            ImgDrawCircleTool tool = new ImgDrawCircleTool();

            try {
                // 图片发送到Django进行识别
                ResponseEntity<String> responseEntity = Threads.detectionRequest(profile + detectionImages, detectionUrl);
                log.info("responseEntity------->" + responseEntity.getBody());
                // json格式的数据转换成数组格式
                detectionLogList = JSON.parseArray(responseEntity.getBody(), DetectionLog.class);
                log.info(detectionLogList.toString());
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            if (StringUtils.isNotNull(detectionLogList)) {
                for (DetectionLog detection : detectionLogList) {
                    if (StringUtils.isNotNull(detection)) {
                        detection.setImagePath(images).setOriginalFileName(file.getOriginalFilename()).setThumPath(images.replace("original", "thum"));
                        String tagNum = ParseString.getTagNum(detection.getTag());
                        log.info("检测结果：" + tagNum);
                        JSONObject jsonObject = JSON.parseObject(tagNum);
                        int num_1 = 0, num_2 = 0, num_3 = 0, num_4 = 0;
                        if (jsonObject.get("1") != null) {
                            num_1 = (int) jsonObject.get("1");
                        }
                        if (jsonObject.get("2") != null) {
                            num_2 = (int) jsonObject.get("2");
                        }
                        if (jsonObject.get("3") != null) {
                            num_3 = (int) jsonObject.get("3");
                        }
                        if (jsonObject.get("4") != null) {
                            num_4 = (int) jsonObject.get("4");
                        }
                        /*画框之后的结果图 resUrl  缩略图 已添加 */
                        List<String> tagList = JSON.parseArray(detection.getTag(), String.class);
                        String resultPath = tool.doDrawRectangle(detection.getCorner(), tagList, profile + detectionImages, num_1, num_2, num_3, num_4,0,0,0,0,0,0,0,0,0,0,0).replace(profile, Constants.RESOURCE_PREFIX);

                        detection.setTag(ParseString.getTagNum(detection.getTag())).setResultPath(resultPath).setImgTime(imgCreateTime);
                        log.info(detection.toString());
                        modelService.insertDetectionLog(detection);
                    }
                }
                return AjaxResult.success(detectionLogList);
            }
            return AjaxResult.success("再试一次");
        }
        return AjaxResult.error("上传图片异常");
    }

    /**
     * 查询出所有结果
     *
     * @param detectionLog 对象
     * @return
     */
    @ApiOperation(value = "查询已下载的insect图片列表,根据时间查找的时候，加上beginTime和end参数示例如下：" , notes = "http://192.168.1.217:8989/detection/getHistoryImg?params%5BbeginTime%5D=2021-08-28&params%5BendTime%5D=2021-09-03")
    @GetMapping("/getHistoryImg")
    public TableDataInfo sendFront(DetectionLog detectionLog) {
        startPage();
        List<DetectionLog> detectionLogList = modelService.selectDetectionLogList(detectionLog);
        return getDataTable(detectionLogList);
    }



}
